package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class ChatClient {

	private Socket server;

	public void run() {
		try {
			//server = new Socket(InetAddress.getLocalHost(), 5678);
			//server = new Socket("137.64.32.136", 7653);
			server = new Socket("127.0.0.1", 7653);
			new Thread(createRunable()).start();
			PrintWriter out = new PrintWriter(new OutputStreamWriter(
					server.getOutputStream()));
			BufferedReader wt = new BufferedReader(new InputStreamReader(
					System.in));
			while (true) {
				String str = wt.readLine();
				// 控制台默认是gbk编码，
				// gbk转为utf8时，末尾为汉字字符串为汉字，
				// 并且个数为单数，则最后一个汉字乱码
				str = new String(str.getBytes("gbk"), "utf-8");
				System.out.println(str);
				if(out!=null){
					out.println(str);
					out.flush();
				}else{
					System.out.println("断开。。。");
					break;
				}
				
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ChatClient client = new ChatClient();
		client.run();
	}

	private Runnable createRunable() {
		return new Runnable() {

			public void run() {
				try {
					BufferedReader in = new BufferedReader(
							new InputStreamReader(server.getInputStream()));
					while (true) {
						if (in != null) {
							System.out.println(in.readLine());
						} else {
							System.out.println("断开。。。");
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		};
	}

}
